import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  Logger,
  HttpStatus,
  NotFoundException,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { QueryFailedError, TypeORMError } from 'typeorm';
import { fail } from '@/utils/globalResponse';
import { JsonWebTokenError, TokenExpiredError } from 'jsonwebtoken';

@Catch()
export class ExFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();

    let status: number;

    let message: string;

    if (exception instanceof NotFoundException) {
      status = HttpStatus.NOT_FOUND;
      message = exception.message ?? 'not found this handler';
    }
    // 校验异常
    if (exception instanceof QueryFailedError) {
      status = HttpStatus.BAD_REQUEST;
      // console.log('校验异常', exception);
      message = '参数错误: ' + exception.message ?? '参数错误,请检查';
    }

    if (exception instanceof HttpException) {
      status = exception.getStatus() ?? HttpStatus.INTERNAL_SERVER_ERROR;
      // console.log('HttpException:', exception);
      message = exception.message ?? 'INTERNAL_SERVER_ERROR';
    }
    if (exception instanceof TypeORMError) {
      status = 10001;
      // console.log('HttpException:', exception);
      message = '  error ';
    }

    response.json(fail(status, message));
    // console.log(ctx);
    /*   response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
    }); */
    Logger.error(
      '请求地址: ' +
        request.url +
        '  请求方法: ' +
        request.method +
        ' 错误: ' +
        exception,
    );
  }
}
